<template>
  <div class="leftbar">
    <ul>
      <li
        :class="isActive == 'findmusic' ? 'isActive' : ''"
        @click="toFindMusicPage"
      >
        发现音乐
      </li>
      <li>播客</li>
      <li>视频</li>
      <li :class="isActive == 'follow' ? 'isActive' : ''" @click="toFollowPage">
        关注
      </li>
      <li>直播</li>
      <li>私人FM</li>
    </ul>

    <div class="title">我的音乐</div>

    <ul>
      <li>
        <img src="../../../assets/img/下载.png" /><span>本地音乐与下载</span>
      </li>
      <li
        :class="isActive == 'recently' ? 'isActive' : ''"
        @click="toRecentlyPlayPage"
      >
        <img src="../../../assets/img/历史播放.png" /><span>最近播放</span>
      </li>
      <li :class="isActive == 'cloud' ? 'isActive' : ''" @click="toCloudPage">
        <img src="../../../assets/img/云.png" /><span>我的音乐云盘</span>
      </li>
      <li><img src="../../../assets/img/音乐.png" /><span>我的播客</span></li>

      <li><img src="../../../assets/img/用户.png" /><span>我的收藏</span></li>
    </ul>

    <!-- 登录退出按钮 -->
    <div class="login">
      <el-button
        type="danger"
        @click="loginDialogVisible = true"
        v-if="loginOrLogout"
        >登入</el-button
      >
      <el-button v-else type="info" @click="logoutDialogVisible = true"
        >退出</el-button
      >
    </div>

    <div class="title" v-if="!loginOrLogout">创建的歌单</div>
    <!-- 用户的个人歌单 -->
    <ul v-if="!loginOrLogout">
      <li
        :class="isActive == music.id ? 'isActive' : ''"
        v-for="music in createdList"
        :key="music.id"
        @click="toSonglistPage(music.id)"
      >
        {{ music.name }}
      </li>
    </ul>

    <div class="title" v-if="!loginOrLogout">收藏的歌单</div>
    <!-- 用户的个人歌单 -->
    <ul v-if="!loginOrLogout">
      <li
        :class="isActive == music.id ? 'isActive' : ''"
        v-for="music in subscribedList"
        :key="music.id"
        @click="toSonglistPage(music.id)"
      >
        {{ music.name }}
      </li>
    </ul>

    <!-- 登入对话对话框 -->
    <el-dialog
      :title="loginTog ? '二维码登入' : '验证码登入'"
      :visible.sync="loginDialogVisible"
      width="50%"
      @close="resetPhoneForm"
    >
      <el-button type="primary" @click="Tog">点击可切换登入方式</el-button>

      <br /><br />
      <!-- 手机扫码登入 -->
      <div v-if="loginTog">
        <el-image
          style="width: 200px; height: 200px"
          :src="loginCode"
          fit="fill"
        ></el-image>
        <el-button type="primary" @click="loginQRCode">刷新二维码</el-button>
      </div>

      <!-- 手机密码、验证码登入 -->
      <div v-else>
        <el-form
          ref="phoneRuleForm"
          :model="phoneForm"
          label-width="0px"
          class="login_form"
        >
          <el-form-item label="手机号码：" label-width="160px">
            <el-input
              v-model="phoneForm.number"
              placeholder="输入11位数的手机号"
            ></el-input>
          </el-form-item>
          <el-form-item label="输入密码：" label-width="160px">
            <el-input
              v-model="phoneForm.password"
              show-password
              placeholder="输入密码"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="操作"
            label-width="160px"
            style="display: flex; justifycontent: spaceBetween"
          >
            <el-button
              type="primary"
              :disabled="
                phoneForm.number.length === 11 && phoneForm.password != ''
                  ? false
                  : true
              "
              @click="loginPhonePassword"
              >密码登录</el-button
            >
          </el-form-item>
          <el-form-item label="获取验证码" label-width="160px">
            <el-button
              type="primary"
              :disabled="
                phoneForm.number.length === 11 && phoneForm.password == ''
                  ? false
                  : true
              "
              @click="getPhoneCode"
              >获取验证码</el-button
            >
          </el-form-item>
          <el-form-item
            label="手机验证码："
            label-width="160px"
            prop="phonecode"
          >
            <el-input
              v-model="phoneForm.phoneCode"
              placeholder="输入验证码"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="操作"
            label-width="160px"
            style="display: flex; justifycontent: spaceBetween"
          >
            <el-button
              type="primary"
              :disabled="
                phoneForm.number.length === 11 &&
                phoneForm.phoneCode != '' &&
                phoneForm.password == ''
                  ? false
                  : true
              "
              @click="loginPhoneCode"
              >登录</el-button
            >
          </el-form-item>
          <el-form-item label="操作" label-width="160px">
            <el-button @click="resetPhoneForm"> 重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <span slot="footer">
        <el-button @click="resetPhoneForm">取 消</el-button>
      </span>
    </el-dialog>

    <!-- 退出对话框 -->
    <el-dialog title="是否退出" :visible.sync="logoutDialogVisible" width="50%">
      <span slot="footer">
        <el-button type="primary" @click="logout">确认</el-button>
        <el-button @click="logoutDialogVisible = false">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { mapState, mapMutations } from 'vuex'

export default {
  name: 'leftbar',
  data() {
    return {
      // 登入对话框显示与否
      loginDialogVisible: false,
      // 二维码登入和验证码登入切换
      loginTog: true,
      // 登入二维码地址
      loginCode: '',
      phoneForm: {
        // 手机号
        number: '',
        // 密码
        password: '',
        // 手机验证码
        phoneCode: '',
      },
      // 用户信息
      userInfo: {},
      // 登入与退出按钮显示与否
      loginOrLogout: true,
      // 退出对话框显示与否
      logoutDialogVisible: false,
      // 歌单列表
      musiclist: [],
      // 我创建的歌单
      createdList: [],
      // 我收藏的歌单
      subscribedList: [],
    }
  },
  created() {
    this.loginTogLogout()
    setTimeout(() => {
      this.getLoginStatus()
    }, 100)
  },
  computed: {
    ...mapState(['userId', 'isActive']),
  },
  methods: {
    ...mapMutations([
      'changePath',
      'initUsereId',
      'changeIsActive',
      'changeSonglistId',
    ]),

    // 切换登录方式
    Tog() {
      this.loginTog = !this.loginTog
    },
    // 控制登录、退出按钮的显示与否
    async loginTogLogout() {
      if (!window.sessionStorage.getItem('token')) {
        await this.$http({
          url: `/logout?timestamp=${Date.now()}`,
          withCredentials: true, //关键
        })
        return (this.loginOrLogout = true)
      }
      return (this.loginOrLogout = false)
    },

    // 二维码登录
    async loginQRCode() {
      this.loginDialogVisible = true

      // 获取二维码的 key
      const { data: res } = await this.$http({
        url: `/login/qr/key?timestamp=${Date.now()}`,
        withCredentials: true, //关键
      })
      console.log(res)
      const key = res.data.unikey

      // 发起二维码请求，得到二维码图片
      const { data: res2 } = await this.$http({
        url: `/login/qr/create?key=${key}&qrimg=true&?timestamp=${Date.now()}`,
        withCredentials: true, //关键
      })
      console.log(res2)
      this.loginCode = res2.data.qrimg

      //  发起二维码登录请求
      let timer = setInterval(async () => {
        const { data: res } = await this.$http({
          url: `/login/qr/check?key=${key}&timestamp=${Date.now()}`,
          withCredentials: true, //关键
        })
        console.log(res)

        // 判断二维码当前状态
        if (res.code === 800) {
          clearInterval(timer)
          this.$message.error('二维码过期，请重新获取！')
        }
        if (res.code === 801) {
          this.$message.warning('等待扫描')
        }
        if (res.code === 802) {
          this.$message.warning('登录中！')
        }
        if (res.code === 803) {
          clearInterval(timer)
          this.$message.success('登入成功！')

          window.sessionStorage.setItem('token', res.cookie)
          this.loginDialogVisible = false
          this.loginTogLogout()
          this.getLoginStatus()
        }
      }, 5000)
    },

    // 手机密码登录
    async loginPhonePassword() {
      // 发起登入请求，获取信息
      const { data: res } = await this.$http({
        url: `/login/cellphone?phone=${this.phoneForm.number}&password=${
          this.phoneForm.password
        }&timestamp=${Date.now()}`,
        withCredentials: true, //关键
      })
      // console.log(res)
      if (res.code != 200) {
        return this.$message.error('登录失败！')
      }
      this.$message.success('登录成功！')

      window.sessionStorage.setItem('token', res.token)
      this.resetPhoneForm()
      this.loginDialogVisible = false
      this.loginTogLogout()
      this.getLoginStatus()
    },

    // 获取验证码
    async getPhoneCode() {
      const { data: res } = await this.$http({
        url: `/captcha/sent?phone=${this.phoneForm.number}&ctcode=86`,
        withCredentials: true, //关键
      })
      console.log(res)
    },
    // 验证验证码
    async checkPhoneCode() {
      const { data: res } = await this.$http({
        url: `/captcha/verify?phone=${this.phoneForm.number}&captcha=${this.phoneForm.phoneCode}`,
        withCredentials: true, //关键
      })
      console.log(res)

      const isLogin = () => {
        if (res.code == 200) {
          return true
        }
        return false
      }
      return isLogin
    },
    // 手机验证码登录
    async loginPhoneCode() {
      const islogin = this.checkPhoneCode()
      console.log(islogin)
      // 判断验证码是否正确
      if (!islogin) {
        return this.$message.error('验证码错误！')
      }
      this.$message.success('验证码正确！')

      // 发起登入请求，获取信息
      const { data: res } = await this.$http({
        url: `/login/cellphone?phone=${this.phoneForm.number}&captcha=${this.phoneForm.phoneCode}`,
        withCredentials: true, //关键
      })
      console.log(res)

      window.sessionStorage.setItem('token', res.token)
      this.resetPhoneForm()
      this.loginDialogVisible = false
      this.loginTogLogout()
      this.getLoginStatus()
    },

    // 监听账号是否登入成功,成功则会保存信息
    async getLoginStatus() {
      const { data: res } = await this.$http({
        url: `/login/status?timestamp=${Date.now()}`,
        withCredentials: true, //关键
      })
      // console.log(res.data)
      if (res.data.profile == null) {
        return console.log('未登录，暂无数据')
      }
      // 登录成功后，能返回数据，数据能够储存
      this.userInfo = res.data
      // 传值给父组件
      this.$emit('getUserDate', this.userInfo)
      // this.getUserPlaylist(this.userInfo.profile.userId)

      this.initUsereId(this.userInfo.profile.userId)
      this.getUserPlaylist(this.userId)
    },
    // 清空手机密码、验证码登录表单
    resetPhoneForm() {
      this.phoneForm.number = ''
      this.phoneForm.password = ''
      this.phoneForm.phoneCode = ''
    },
    // 退出登录
    async logout() {
      const { data: res } = await this.$http({
        url: `/logout?timestamp=${Date.now()}`,
        withCredentials: true, //关键
      })
      console.log(res)
      if (res.code != 200) {
        return this.$message.error('退出失败！')
      }
      this.$message.success('退出成功！')
      window.sessionStorage.clear('token')
      this.loginOrLogout = true
      this.logoutDialogVisible = false
      location.reload()
    },

    // 获取用户歌单
    async getUserPlaylist(userId) {
      const { data: res } = await this.$http({
        url: `/user/playlist?uid=${userId}`,
        withCredentials: true, //关键
      })
      // console.log(res)

      this.musiclist = res.playlist
      // console.log(this.musiclist)
      this.getPlaylistAboutInfo(this.musiclist)
    },
    // 提取歌单相关信息
    getPlaylistAboutInfo(list) {
      let tmepCreatedListDatas = []
      let tmepSubscribedListDatas = []

      list.map((item) => {
        let listObj = {}

        /**
         * 歌单id id
         * 歌单名称 name
         */
        listObj.id = item.id
        listObj.name = item.name

        if (item.subscribed) {
          return tmepSubscribedListDatas.push(listObj)
        } else {
          return tmepCreatedListDatas.push(listObj)
        }
      })

      this.createdList = tmepCreatedListDatas
      this.subscribedList = tmepSubscribedListDatas
      // console.log(this.createdList)
      // console.log(this.subscribedList)
    },

    // 传递 歌单数据，并跳转到歌单页面
    toSonglistPage(songlistId) {
      const info = {
        path: '/view/songlist',
        isActive: songlistId,
        songlistId: songlistId,
      }

      this.changePath(info.path)
      this.changeIsActive(info.songlistId)
      this.changeSonglistId(info.songlistId)

      this.$emit('getSonglistId')
    },
    // 传递用户数据， 并跳转到最近播放页面
    toRecentlyPlayPage() {
      if (!window.sessionStorage.getItem('token')) {
        return this.$message.warning('请先登录！')
      }

      const info = {
        path: '/view/recentlyplay',
        isActive: 'recently',
      }

      this.changePath(info.path)
      this.changeIsActive(info.isActive)

      this.$emit('getRecentlyPlayPageInfo')
    },
    // 传递用户数据，并跳转到关注页面
    toFollowPage() {
      if (!window.sessionStorage.getItem('token')) {
        return this.$message.warning('请先登录！')
      }

      const info = {
        path: '/view/follow',
        isActive: 'follow',
      }

      this.changePath(info.path)
      this.changeIsActive(info.isActive)

      this.$emit('getFollowPageInfo')
    },
    // 传递用户数据，并跳转到我的音乐云盘页面
    toCloudPage() {
      if (!window.sessionStorage.getItem('token')) {
        return this.$message.warning('请先登录！')
      }

      const info = {
        path: '/view/cloud',
        isActive: 'cloud',
      }

      this.changePath(info.path)
      this.changeIsActive(info.isActive)

      this.$emit('getCloudPageInfo')
    },
    // 传递路由路径
    toFindMusicPage() {
      const info = {
        path: '/view/find',
        isActive: 'findmusic',
      }

      this.changePath(info.path)
      this.changeIsActive(info.isActive)

      this.$emit('getFindMusicPageInfo')
    },
  },
}
</script>

<style lang="less" scoped>
.leftbar {
  width: 220px;
  height: 540px;
  background-color: white;
  display: flex;
  flex-direction: column;
  overflow: auto;
  border-right: 1px solid rgb(196, 194, 194);
}

ul {
  margin: 0;
  padding: 0;
}
li {
  list-style: none;
  padding-left: 24px;
  padding-top: 8px;
  padding-bottom: 8px;
  font-size: 16px;
  font-weight: 350;
  margin-left: 6px;
  margin-right: 6px;
  // 以下三行样式：文本不换行，多余的字符用省略号代替
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  cursor: pointer;
  > span {
    padding-left: 6px;
    position: relative;
    top: -5px;
  }
}
li:hover {
  background-color: #f6f6f7;
}

.isActive {
  font-size: 18px;
  font-weight: 900;
  background-color: #f6f6f7;
}

.title {
  padding-left: 24px;
  padding-top: 8px;
  padding-bottom: 10px;
  font-weight: 100;
  color: #999999;
}

.login {
  margin: 0 auto;
  margin-top: 12px;
  margin-bottom: 12px;
}

/deep/ .el-input__inner {
  width: 360px;
}
</style>